import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
  InternalAxiosRequestConfig,
} from 'axios'
import { ElMessage } from 'element-plus'
import cookie from 'js-cookie'
import authService from './authService'



// 定义响应数据结构
interface ResponseData<T = any> {
  code: number
  msg: string
  message?: string
  data?: T
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 15000, // 请求超时时间
})

// http request 拦截器
service.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    // 使用authService处理token
    return await authService.processRequest(config)
  },
  (err: AxiosError) => {
    return Promise.reject(err)
  },
)

// http response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ResponseData>) => {
    if (response.data.code !== 200) {
      ElMessage({
        message: response.data.msg || response.data.message || '请求错误',
        type: 'error',
        duration: 5 * 1000,
      })
      return Promise.reject(response.data)
    }
    return response
  },
  async (error: AxiosError) => {
    const originalRequest: any = error.config

    // 如果是401错误且不是刷新token的请求
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true

      try {
        // 刷新token
        const newToken = await authService.refreshAccessToken()

        // 重试原始请求
        originalRequest.headers.Authorization = newToken
        return service(originalRequest)
      } catch (refreshError) {
        // 刷新失败，显示错误消息
        ElMessage({
          message: '登录已过期，请重新登录',
          type: 'error',
          duration: 5 * 1000,
        })
        // 跳转到登录页并添加显示登录对话框的参数
        window.location.href = '/?showLogin=true'
        return Promise.reject(refreshError)
      }
    }

    ElMessage({
      message: error.message || '网络错误',
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  },
)

export default service
